package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.DictConsoleService;
import com.ibeetl.admin.console.service.UserConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.EssentialInformation;
import com.ibeetl.cms.entity.KeyInformation;
import com.ibeetl.cms.service.BusinessProcessService;
import com.ibeetl.cms.service.EssentialInformationService;
import com.ibeetl.cms.service.KeyInformationService;
import com.ibeetl.cms.util.BusinessTypeConstant;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.web.query.KeyInformationQuery;
import com.ibeetl.cms.web.query2.KeyInformationEnterpriseQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * KeyInformation 接口
 * 关键信息变更
 */
@Controller
public class KeyInformationController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/keyInformation";


    @Autowired private KeyInformationService keyInformationService;

    @Autowired
    FileService fileService;

    @Autowired
    CorePlatformService platformService;

    @Autowired
    private EssentialInformationService essentialInformationService;

    @Autowired
    private BusinessProcessService businessProcessService;

    @Autowired
    UserConsoleService userConsoleService;

    @Autowired
    private DictConsoleService dictConsoleService;

    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @ResponseBody
    public ModelAndView index(String roleName,String year) {
        ModelAndView view;
        if (roleName.equals("shenbao")) {
            view = new ModelAndView("/cms/keyInformation/index.html") ;
            view.addObject("search", KeyInformationQuery.class.getName());
        } else if (roleName.equals("shouli")) {
            view = new ModelAndView("/cms/keyInformation/enterpriseindex.html");
            view.addObject("search", KeyInformationEnterpriseQuery.class.getName());
        } else {//(roleName.equals("chushen"))
            view = new ModelAndView("/cms/keyInformation/chushenindex.html");
            view.addObject("search", KeyInformationQuery.class.getName());
        }

        if (roleName.equals("chushen")) {
            KeyInformationQuery condtion = new KeyInformationQuery();
            if(StringUtils.isEmpty(year)){
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            view.addObject("year",year);
            condtion.setYear(year);

            /**
             * 获取本年度所有有申报的公司
             */
            List<KeyInformation> lists = keyInformationService.queryCompany(condtion);
            Map<Integer, String> companies = new HashMap<>(16);
            int count = 0;
            for (KeyInformation keyInformation : lists) {
                if(keyInformation.getCompanyId() == null){
                    continue;
                }
                if (count == 0) {
                    keyInformation.setRoleName(roleName);
                }
                companies.put(keyInformation.getCompanyId(), keyInformation.getCurrentWorkingEnterprise());
                count++;
            }
            view.addObject("companies", companies);

            view.addObject("roleName", roleName);
        }
        return view;
    }

    /**
     * 获取该申报，该公司下的员工
     *
     * @param companyId
     * @return
     */
    @PostMapping(MODEL + "/employees.json")
    @Function("keyInformation.check")
    @ResponseBody
    public JsonResult<PageQuery> employees(String companyId,String year) {
       KeyInformationQuery condtion = new KeyInformationQuery();
        condtion.setCompanyId(companyId);
        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condtion.setYear(year);

        List<String> ids = new ArrayList();
        ids.add(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
        ids.add(ProcessConstant.FIRSTCHECK_STR);
        ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        ids.add(ProcessConstant.COMPANY_ADOPT_STR);

        condtion.setIds(ids);

        PageQuery page = condtion.getPageQuery();
        keyInformationService.queryEmployees(page);
        return JsonResult.success(page);
    }

    @GetMapping(MODEL + "/shenhe.do")
    @Function("keyInformation.check")
    @ResponseBody
    public ModelAndView shenhe(Integer id,String bStateCode,String roleName) {
        ModelAndView view ;
        if(bStateCode.equals(ProcessConstant.TO_FIRSTCHECK) && roleName.equals("chushen")){
            view  =new ModelAndView("/cms/keyInformation/shenheedit.html");
        }else{
            view  = new ModelAndView("/cms/keyInformation/findenterpriseedit.html");
            view.addObject("look",true);
        }
        KeyInformation keyInformation = keyInformationService.queryById(id);
        keyInformation.setRoleName(roleName);
        view.addObject("keyInformation", keyInformation);
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("keyInformation")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/keyInformation/edit.html");
        KeyInformation keyInformation = keyInformationService.queryById(id);
        view.addObject("keyInformation", keyInformation);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("keyInformation")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/keyInformation/add.html");
        Long userid = getUserId();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(userid);
        view.addObject("essentialInformation", essentialInformation);
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("keyInformation")
    @ResponseBody
    public JsonResult<PageQuery> list(KeyInformationQuery condtion){
        Long userid = getUserId();
        condtion.setUserid(userid);
        if(StringUtils.isEmpty(condtion.getYear())){
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            String yearStr = year.toString();
            condtion.setYear(yearStr);
        }
        PageQuery page = condtion.getPageQuery();
        keyInformationService.queryByCondition(page);
        return JsonResult.success(page);
    }

    /**
     * 受理页面数据
     * @param condtion
     * @return
     */
    @PostMapping(MODEL + "/Acceptancelist.json")
    @Function("keyInformation.company")
    @ResponseBody
    public JsonResult<PageQuery> Acceptancelist(KeyInformationQuery condtion) {
        Long userid = getUserId();
        condtion.setUserid(userid);
        if(StringUtils.isEmpty(condtion.getYear())){
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            String yearStr = year.toString();
            condtion.setYear(yearStr);
        }
        PageQuery page = condtion.getPageQuery();

        condtion.setCompanyId(userid.toString());
        if(condtion.getBusinessState()=="" || condtion.getBusinessState()==null){
            condtion.setBusinessState(ProcessConstant.TO_COMPANY);
        }else {
            condtion.setBusinessState(condtion.getBusinessState());
        }
        //查询企业数据
        keyInformationService.findenterprise(page);
        return JsonResult.success(page);
    }

    /**
     * 新增（保存）
     *
     * @param keyInformation
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function("keyInformation")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)KeyInformation keyInformation){
        if(keyInformation.getNewIdNumber().equals("admin")){
            return JsonResult.failMessage("用户名无法修改为admin");
        }
        String yearStr = dictConsoleService.getDeclareYear();
        keyInformation.setYear(yearStr);

        Long userId = getUserId();
        keyInformation.setUserId(userId.intValue());
        keyInformation.setCreationDate(new Date());
        keyInformation.setCompanyId(Math.toIntExact(platformService.getCurrentUser().getCompanyId()));
        keyInformation.setBusinessState(ProcessConstant.WAIT_APPLICATION_STR);
        keyInformation.setBusinessStateCode(ProcessConstant.WAIT_APPLICATION);

        keyInformationService.save(keyInformation);

        //调用增加业务流程数据
        businessProcessService.processInformation(keyInformation.getId(),keyInformation.getBusinessState(),
                keyInformation.getBusinessStateCode(),keyInformation.getHandlingSuggestion(),"成功", BusinessTypeConstant.keyInformation);
        return new JsonResult().success();
    }

    /**
     * 新增（保存并申请）
     *
     * @param keyInformation
     * @return
     */
    @PostMapping(MODEL + "/savedeclaration.json")
    @Function("keyInformation")
    @ResponseBody
    public JsonResult savedeclaration(@Validated(ValidateConfig.ADD.class) KeyInformation keyInformation) {
        if(keyInformation.getNewIdNumber().equals("admin")){
            return JsonResult.failMessage("用户名无法修改为admin");
        }
        String yearStr = dictConsoleService.getDeclareYear();
        keyInformation.setYear(yearStr);

        Long userId = getUserId();
        keyInformation.setUserId(userId.intValue());
        keyInformation.setCreationDate(new Date());
        keyInformation.setDateReporting(new Date());
        keyInformation.setBusinessState(ProcessConstant.TO_COMPANY_STR);
        keyInformation.setCompanyId(Math.toIntExact(platformService.getCurrentUser().getCompanyId()));
        keyInformation.setYear(yearStr);
        keyInformation.setBusinessStateCode(ProcessConstant.TO_COMPANY);

        keyInformationService.save(keyInformation);

        //调用增加业务流程数据
        businessProcessService.processInformation(keyInformation.getId(),keyInformation.getBusinessState(),
                keyInformation.getBusinessStateCode(),keyInformation.getHandlingSuggestion(),"成功",BusinessTypeConstant.keyInformation);
        return new JsonResult().success();
    }

    /**
     * 修改（保存）
     * @param keyInformation
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function("keyInformation")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  KeyInformation keyInformation) {
        keyInformation.setBusinessState(ProcessConstant.WAIT_APPLICATION_STR);
        keyInformation.setBusinessStateCode(ProcessConstant.WAIT_APPLICATION);
        boolean success = keyInformationService.updateTemplate(keyInformation);

        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 修改（保存并申请）
     *
     * @param keyInformation
     * @return
     */
    @PostMapping(MODEL + "/editandsave.json")
    @Function("keyInformation")
    @ResponseBody
    public JsonResult<String> editandsave(@Validated(ValidateConfig.UPDATE.class)  KeyInformation keyInformation) {
        keyInformation.setDateReporting(new Date());

        keyInformation.setBusinessState(ProcessConstant.TO_COMPANY_STR);
        keyInformation.setBusinessStateCode(ProcessConstant.TO_COMPANY);

        boolean success = keyInformationService.updateTemplate(keyInformation);

        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 获得本年度已办任务
     */
    @PostMapping(MODEL + "/firstcheckList.json")
    @ResponseBody
    public JsonResult<PageQuery> firstcheckList(KeyInformationQuery condtion) {
        if(StringUtils.isEmpty(condtion.getYear())){
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            String yearStr = year.toString();
            condtion.setYear(yearStr);
        }
        condtion.setProcessUserId(getUserId());
        condtion.setBusinessType(BusinessTypeConstant.keyInformation);
        PageQuery page = condtion.getPageQuery();
        keyInformationService.queryDoneTask(page);
        return JsonResult.success(page);
    }


    @GetMapping(MODEL + "/view.json")
    @Function("cms.keyInformation.query")
    @ResponseBody
    public JsonResult<KeyInformation>queryInfo(Integer id) {
        KeyInformation keyInformation = keyInformationService.queryById( id);
        return  JsonResult.success(keyInformation);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("keyInformation")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        keyInformationService.batchDelKeyInformation(idList);
        return new JsonResult().success();
    }
    /**
     * 查看页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/findenterprise.do")
    @ResponseBody
    public ModelAndView findenterprise(Integer id) {
        ModelAndView view = new ModelAndView("/cms/keyInformation/findenterpriseedit.html");
        KeyInformation keyInformation = keyInformationService.queryById(id);
        view.addObject("look",true);
        view.addObject("keyInformation", keyInformation);
        return view;
    }



    /**
     * 单位产业人才点击受理页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/acceptance.do")
    @Function("keyInformation.company")
    @ResponseBody
    public ModelAndView acceptance(Integer id) {
        ModelAndView view = new ModelAndView("/cms/keyInformation/acceptance.html");
        KeyInformation keyInformation = keyInformationService.queryById(id);
        view.addObject("keyInformation", keyInformation);
        return view;
    }


    /**
     * 受理终止
     */
    @PostMapping(MODEL + "/Admissibility.json")
    @Function("keyInformation.company")
    @ResponseBody
    public JsonResult<String> Admissibility(@Validated(ValidateConfig.UPDATE.class) KeyInformation keyInformation) {
        keyInformation.setBusinessState(ProcessConstant.TERMINIATE_STR);
        keyInformation.setBusinessStateCode(ProcessConstant.TERMINIATE);
        keyInformation.setProcessResult(ProcessConstant.COMPANY_TERMINIATE_STR);
        boolean success = keyInformationService.updateTemplate(keyInformation);

        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(keyInformation.getId(),keyInformation.getBusinessState(),
                    keyInformation.getBusinessStateCode(),keyInformation.getHandlingSuggestion(),ProcessConstant.COMPANY_TERMINIATE_STR, BusinessTypeConstant.keyInformation);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

//    /**
//     * 初审终止
//     */
//    @PostMapping(MODEL + "/FirstTrialTermination.json")
//    @Function("cms.keyInformation.check")
//    @ResponseBody
//    public JsonResult<String> FirstTrialTermination(@Validated(ValidateConfig.UPDATE.class) KeyInformation keyInformation) {
//        keyInformation.setBusinessState(ProcessConstant.TERMINIATE_STR);
//        keyInformation.setBusinessStateCode(ProcessConstant.TERMINIATE);
//        keyInformation.setProcessResult(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
//        boolean success = keyInformationService.updateTemplate(keyInformation);
//        if (success) {
//            //调用增加业务流程数据
//            businessProcessService.processInformation(keyInformation.getId(),keyInformation.getBusinessState(),
//                    keyInformation.getBusinessStateCode(),keyInformation.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_TERMINIATE_STR, BusinessTypeConstant.keyInformation);
//        } else {
//            return JsonResult.failMessage("保存失败");
//        }
//        return new JsonResult().success();
//    }

    /**
     * 受理退回
     */
    @PostMapping(MODEL + "/AdmissibleReturn.json")
    @Function("keyInformation.company")
    @ResponseBody
    public JsonResult<String> AdmissibleReturn(@Validated(ValidateConfig.UPDATE.class) KeyInformation keyInformation) {
        keyInformation.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
        keyInformation.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        keyInformation.setProcessResult(ProcessConstant.COMPANY_BACK_STR);
        boolean success = keyInformationService.updateTemplate(keyInformation);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(keyInformation.getId(),ProcessConstant.COMPANY_BACK_STR,
                    ProcessConstant.COMPANY_BACK,keyInformation.getHandlingSuggestion(),ProcessConstant.COMPANY_BACK_STR, BusinessTypeConstant.keyInformation);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }

    }

//    /**
//     * 初审退回
//     */
//    @PostMapping(MODEL + "/initialReview.json")
//    @Function("keyInformation.check")
//    @ResponseBody
//    public JsonResult<String> initialReview(@Validated(ValidateConfig.UPDATE.class) KeyInformation keyInformation) {
//        keyInformation.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
//        keyInformation.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
//        keyInformation.setProcessResult(ProcessConstant.FIRSTCHECK_STR);
//        boolean success = keyInformationService.updateTemplate(keyInformation);
//        if (success) {
//            //调用增加业务流程数据
//            businessProcessService.processInformation(keyInformation.getId(),ProcessConstant.FIRSTCHECK_STR,
//                    ProcessConstant.FIRSTCHECK,keyInformation.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_STR, BusinessTypeConstant.keyInformation);
//            //给企业发一条退回信息
//            Message message=new Message();
//            message.setCompanyId(keyInformation.getCompanyId());
//            message.setUserId(keyInformation.getUserId());
//            message.setStatus(-1);
//            message.setContent(keyInformation.getHandlingSuggestion());
//            message.setType(Integer.parseInt(BusinessTypeConstant.keyInformation));
//            message.setCreateDate(new Date());
//            messageService.save(message);
//            return new JsonResult().success();
//        } else {
//            return JsonResult.failMessage("保存失败");
//        }
//    }

    /**
     * 受理通过
     */
    @PostMapping(MODEL + "/AcceptanceOK.json")
    @Function("keyInformation.company")
    @ResponseBody
    public JsonResult<String> AcceptanceOK(@Validated(ValidateConfig.UPDATE.class) KeyInformation keyInformation) {
            keyInformation.setBusinessState(ProcessConstant.DONE_STR);
            keyInformation.setBusinessStateCode(ProcessConstant.DONE);
            keyInformation.setProcessResult(ProcessConstant.COMPANY_ADOPT_STR);
        boolean success = keyInformationService.updateTemplate(keyInformation);
        if (success) {
                //根据user_id修改个人信息的和类型证件号
                essentialInformationService.updateEssentialInformation(keyInformation.getUserId(), keyInformation.getNewIdType(), keyInformation.getNewIdNumber());
                //根据user_id修改登录账户
                CoreUser user = new CoreUser();
                user.setCode(keyInformation.getNewIdNumber());
                user.setId((long) keyInformation.getUserId());
                userConsoleService.updateTemplate(user);
                //调用增加业务流程数据
                businessProcessService.processInformation(keyInformation.getId(), ProcessConstant.COMPANY_ADOPT_STR,
                        ProcessConstant.COMPANY_ADOPT, keyInformation.getHandlingSuggestion(), ProcessConstant.COMPANY_ADOPT_STR, BusinessTypeConstant.keyInformation);
                return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

//    /**
//     * 初审通过
//     */
//    @PostMapping(MODEL + "/FirstTrial.json")
//    @Function("keyInformation.check")
//    @ResponseBody
//    public JsonResult<String> FirstTrial(@Validated(ValidateConfig.UPDATE.class) KeyInformation keyInformation) {
//            String businessType="关键信息变更";
//            List<Sincerity> list=sincerityService.blacklist(keyInformation.getUserId(),keyInformation.getCompanyId());
//            String roleName=roleConsoleService.getRoleName(keyInformation.getUserId());
//            if(!common.judge(roleName,businessType,list,keyInformation.getCompanyId())){
//                return JsonResult.failMessage("黑名单用户，无法通过");
//            }
//            keyInformation.setBusinessState(ProcessConstant.DONE_STR);
//            keyInformation.setBusinessStateCode(ProcessConstant.DONE);
//            keyInformation.setProcessResult(ProcessConstant.FIRSTCHECK_ADOPT_STR);
//        boolean success = keyInformationService.updateTemplate(keyInformation);
//        if (success) {
//            //修改基本信息的证件类型和号码
//            essentialInformationService.updateEssentialInformation(keyInformation.getUserId(),keyInformation.getNewIdType(),keyInformation.getNewIdNumber());
//            //调用增加业务流程数据
//            businessProcessService.processInformation(keyInformation.getId(),ProcessConstant.FIRSTCHECK_ADOPT_STR,
//                    ProcessConstant.FIRSTCHECK_ADOPT,keyInformation.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_ADOPT_STR, BusinessTypeConstant.keyInformation);
//            return new JsonResult().success();
//        } else {
//            return JsonResult.failMessage("保存失败");
//        }
//
//    }


// 人才公共方法(所有)

    /**
     * 公共方法
     * 用于获取登录ID
     *
     * @return
     */
    public Long getUserId() {
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        return userId;
    }
}
